package utils;

import model.TreeVo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
 
/**
 * <Description>
 *
 * @author CJJ
 * @version 1.0
 * @createDate 2020/06/29 9:09
 */
public class TreeUtil<T extends TreeVo> {
 
    /**
     * 空间换时间 将同级list转成树形对象
     *
     * @param list
     * @return
     */
    public synchronized T peerToLevel(List<T> list) {
        //SysConstants.TREE_ROOT_ID 自定义根节点id
        T root = (T) new TreeVo<T>("-1");
        List<T> parentList = list.stream().filter(l -> l.getParentId().equals(root.getId())).collect(Collectors.toList());
        list.removeAll(parentList);
        convert(parentList, list);
        root.getChildren().addAll(parentList);
        return root;
    }
 
    /**
     * 转换递归
     * @param parentList
     * @param nodeList
     */
    private synchronized void convert(List<T> parentList, List<T> nodeList) {
        List<T> tempParentList = new ArrayList<>();
        List<T> tempNodeList = new ArrayList<>();
        parentList.forEach(parent -> {
            nodeList.forEach(
                    node -> {
                        if (node.getParentId().equals(parent.getId())) {
                            parent.getChildren().add(node);
                            tempNodeList.add(node);
                            tempParentList.add(node);
                        }
                    }
            );
 
        });
        nodeList.removeAll(tempNodeList);
        if (!nodeList.isEmpty()) {
            convert(tempParentList, nodeList);
        }
    }
 
    public static void main(String[] args) {
        TreeVo node = new TreeVo("0", "-1", "0");
        TreeVo node1 = new TreeVo("1", "-1", "1");
        TreeVo node2 = new TreeVo("2", "0", "2");
        TreeVo node3 = new TreeVo("3", "0", "3");
        TreeVo node4 = new TreeVo("4", "1", "4");
        TreeVo node5 = new TreeVo("5", "3", "5");
        TreeVo node6 = new TreeVo("6", "4", "6");
        TreeVo node7 = new TreeVo("7", "5", "7");
        TreeVo node8 = new TreeVo("8", "5", "8");
        ArrayList<TreeVo> treeVos = new ArrayList<>();
        treeVos.addAll(Arrays.asList(node, node1, node2, node3, node4, node5, node6, node7, node8));


        TreeUtil<TreeVo> treeUtil = new TreeUtil<>();
        TreeVo root = treeUtil.peerToLevel(treeVos);
        System.out.println(root.toString());
    }
}